package com.example.animalrescuedemo;

import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.example.animalrescuedemo.model.AnimalBean;
import com.jensjansson.pagedtable.PagedTable;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.theme.ThemeDisplay;
import com.vaadin.Application;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.gwt.server.PortletApplicationContext.PortletListener;
import com.vaadin.terminal.gwt.server.PortletRequestListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.PopupView;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TabSheet.SelectedTabChangeEvent;
import com.vaadin.ui.TabSheet.SelectedTabChangeListener;
import com.vaadin.ui.TabSheet.Tab;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class AnimalrescuedemoApplication extends Application implements
		SelectedTabChangeListener, ClickListener, PortletListener,
		PortletRequestListener {

	private PortletRequest request;
	private String contextPath; 
	private ThemeDisplay themeDisplay;
	private Window mainWindow;
	private PagedTable table = new PagedTable("Search Result");
	private List<AnimalBean> animalList = new ArrayList<AnimalBean>();
	private Button backButton = new Button("Back");
	private Window subwindow;
	private Label description = new Label("");
	
	@Override
	public void init() {
		addComponents();
	}

	public void addComponents() {
		mainWindow = new Window("Hellovaadintest Application");
		populateAnimalList();
		table.addContainerProperty("Nominee Id", String.class, null);
		table.addContainerProperty("Nominee Name", PopupView.class, null);
		table.addContainerProperty("Location", String.class, null);
		table.addContainerProperty("Vote", Button.class, null);
		table.setSelectable(true);
		table.setImmediate(true);
		description.setContentMode(Label.CONTENT_XHTML);
		
		table.addListener(new Table.ValueChangeListener() {
			public void valueChange(ValueChangeEvent event) {
				Object value = event.getProperty().getValue();
				if (null == value) {
					description.setValue("No Description");
				} else {
					description.setValue("Description : " + value);
				}
			}
		});

		for (AnimalBean animal : animalList) {
			Button voteButton = new Button("Vote");
			voteButton.addListener(this);
			voteButton.setData(animal.getName());
			Label content = new Label(animal.getDescription());
			content.setWidth("300px");
			content.setHeight("80px");

			PopupView popup = new PopupView(animal.getName(), content);
			popup.setHideOnMouseOut(false);
			 
			String tableValue = "<table> <tr> <td><img width='50px' height='50px' src='"+animal.getImgPath() + "'></img> &nbsp;&nbsp;&nbsp;&nbsp;</td> <td>&nbsp;&nbsp;" + animal.getDescription()+"</td> </tr> </table>";
			
			table.addItem(
					new Object[] { animal.getState(), popup,
							animal.getLocation(), voteButton },
							tableValue);
		}

		table.setWidth("100%");
		table.setHeight("250px");
		
		mainWindow.addComponent(table.createControls());
		mainWindow.addComponent(table);
		mainWindow.addComponent(table.createControls());
		mainWindow.addComponent(description);

		
		
		setMainWindow(mainWindow);
		backButton.addListener(new ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				mainWindow.removeAllComponents();
				mainWindow.addComponent(table);
				mainWindow.addComponent(description);
				mainWindow.requestRepaintAll();
			}
		});
	}

	public void selectedTabChange(SelectedTabChangeEvent event) {
		TabSheet tabsheet = event.getTabSheet();
		Tab tab = tabsheet.getTab(tabsheet.getSelectedTab());
		if (tab != null) {
			getMainWindow().showNotification(
					"Selected tab: " + tab.getCaption());
		}
	}

	@Override
	public void buttonClick(Button.ClickEvent event) {
		themeDisplay = (ThemeDisplay) request
				.getAttribute(WebKeys.THEME_DISPLAY);
		User user = themeDisplay.getUser();
		if (themeDisplay.isSignedIn()) {
			/*
			 * Business logic goes here once the user logged In and click the Vote button.
			 */
			Button voteButton = event.getButton();
			voteButton.setCaption("Thanks for vote");
			voteButton.setEnabled(false);
			String msgString = "Thank you <b>" + user.getFullName()
					+ ",</b> for Voting to Shelter <b>"
					+ (String) voteButton.getData()+"</b>";
			openNotificationWindow(msgString);

		} else {
			/*
			 * Business logic goes here once the user id Not logged In and click the Vote button.
			 */
			openNotificationWindow("You are not logged in! Please Login to vote.");
		}
	}

	@Override
	public void handleRenderRequest(RenderRequest request,
			RenderResponse response) {
	}

	@Override
	public void handleActionRequest(ActionRequest request,
			ActionResponse response) {
	}

	@Override
	public void onRequestStart(PortletRequest request, PortletResponse response) {
		this.request = request;
		this.contextPath = request.getContextPath();

	}

	@Override
	public void onRequestEnd(PortletRequest request, PortletResponse response) {

	}

	/**
	 * This is used to get the hard coded objects to display in the table component
	 */
	private void populateAnimalList() {
		animalList.add(new AnimalBean("AK", "Friends of Pets", "AK",
				"Anchorage", "I had already adopted a cat from the shelter but loved to" +
						" look at the ones left behind. The shelter was having some trouble" +
						" and needed me to take one of the cats to foster at home. Pretty Bella," +
						" a Russian Blue, was brought into the shelter with her two babies." +
						" She was a great mother and had a wonderful disposition." +
						" I ended up keeping this beautiful girl.", contextPath + "/images/image1.jpg"));
		animalList.add(new AnimalBean("AL", "Prattville/Autauga Human Society",
				"AL", "Prattville",
				"I went to a local no kill shelter looking for" +
				" a cat to adopt. I'd always had animals around growing up and missed having one" +
				"around as I began my new job in Hartford, CT. The room was full and I had no way" +
				" to choose. I simply sat on the floor to see what happened. This gray tabby with " +
				"the BIG green eyes jumped in my lap and started to purr. The caretaker said This is" +
				" Jonathan. He is going to be our featured cat in the next newsletter ", contextPath + "/images/image2.jpeg"));
		animalList.add(new AnimalBean("AR", "Wynne Friends of Animals", "AR",
				"Wynne", "We had just lost our little 17 year old Shih Tzu Bbop and our hearts were broken." +
						" I decided we needed to fill that aching void, so I started looking for a new fur" +
						" baby. On the internet was this picture of this sweet face, and oh those big eyes." +
						" I filled out an application and got to go see him and totally fell in love.", contextPath + "/images/image3.jpg"));
		animalList.add(new AnimalBean("AZ",
				"Humane Society of Southern Arizona", "AZ", "Tucson",
				"After our dalmatian passed on in 2008 we adopted Piper our white terrier a few months later " +
				"when she was 10 months old. She had been rescued from KY and was brought to NJ." +
				" Then, in 2011 we acquired Scooter. His owner had to give him up for adoption;" +
				" we don't why. It's OK, because both of these cuties are all ours and give us all " +
				"the love in the world!", contextPath + "/images/image6.jpg"));
		animalList.add(new AnimalBean("CA", "Medfly Brigade Basenji Rescue",
				"CA", "Acton", "In 2003 I found her-a part Maine Coon-wandering in a park across the street from where I lived." +
						" I thought maybe she had gotten out from someone's home and couldn't find her way back because she was" +
						" so friendly and approaching everyone. So I took her to the Toronto Humane Society to make sure that she" +
						" wasn't lost and had a frantic owner out there somewhere looking for her.", contextPath + "/images/image4.jpg"));
		animalList.add(new AnimalBean("CO", "National Mill Dog Rescue", "CO",
				"Colorado Springs", "Webster is a pitbull/boxer mix who steals the hearts of everyone he meets." +
						" When my husband and I first saw Webbie at a local shelter, we were hesitant " +
						"to adopt a bully breed but decided to meet with Webster and his foster father anyway." +
						" That was the best best decision we could have made. Webster instantly crawled into my lap " +
						"and fell asleep while we pet him.", contextPath + "/images/image5.jpg"));
		animalList.add(new AnimalBean("CT",
				"Meriden Humane Society", "CT", "Meriden",
				"We were told that Maggie had been adopted out 3 times and returned 3 times due to her unfriendly nature." +
				" She was to be put down the next day so we took her home to give her a 4th chance.", contextPath + "/images/image6.jpg"));
		animalList.add(new AnimalBean("DC", "Lucky Dog Animal Rescue",
				"DC", "Washington", "I was sitting in the Vet's to get insulin for Cocoa," +
						" when a woman walked in holding a kitten. She told everyone that " +
						"a man had thrown him from his car and she had rescued him, but was allergic" +
						" so she couldn't keep him. A man called and asked his wife if they " +
						"could adopt and she said NO. This happened several times and I didn't say a word", contextPath + "/images/image7.jpg"));
		
		animalList.add(new AnimalBean("DE", "Forgotten Cats Inc.",
				"DE", "Claymont", "I was sitting in the Vet's to get insulin for Cocoa," +
						" when a woman walked in holding a kitten. She told everyone that " +
						"a man had thrown him from his car and she had rescued him, but was allergic" +
						" so she couldn't keep him. A man called and asked his wife if they " +
						"could adopt and she said NO. This happened several times and I didn't say a word", contextPath + "/images/image1.jpg"));
		animalList.add(new AnimalBean("FL", "Pet Rescue by Judy",
				"FL", "Sanford", "I was sitting in the Vet's to get insulin for Cocoa," +
						" when a woman walked in holding a kitten. She told everyone that " +
						"a man had thrown him from his car and she had rescued him, but was allergic" +
						" so she couldn't keep him. A man called and asked his wife if they " +
						"could adopt and she said NO. This happened several times and I didn't say a word", contextPath + "/images/image2.jpeg"));
		animalList.add(new AnimalBean("ID", "Boise Bully Breed Rescue",
				"ID", "Boise", "I was sitting in the Vet's to get insulin for Cocoa," +
						" when a woman walked in holding a kitten. She told everyone that " +
						"a man had thrown him from his car and she had rescued him, but was allergic" +
						" so she couldn't keep him. A man called and asked his wife if they " +
						"could adopt and she said NO. This happened several times and I didn't say a word", contextPath + "/images/image5.jpg"));
	}

	/**
	 * This is to display some notification message if User is logged in or not.
	 * @param msgString
	 */
	private void openNotificationWindow(String msgString) {
		subwindow = new Window("Voting Notification");
		subwindow.setModal(true);
		subwindow.setHeight("50px");
		subwindow.setWidth("300px");

		VerticalLayout layout = (VerticalLayout) subwindow.getContent();
		layout.setMargin(true);
		layout.setSpacing(true);

		Label message = new Label(msgString);
		message.setContentMode(Label.CONTENT_XHTML);
		subwindow.addComponent(message);
		
		String mylogin="/c/portal/login";
		Link loginLink = new Link("Click here to Login", new ExternalResource(themeDisplay.getPortalURL()+mylogin));
		
		Button close = new Button("Close", new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				(subwindow.getParent()).removeWindow(subwindow);
			}
		});
		if(!themeDisplay.isSignedIn()){
			layout.addComponent(loginLink);
		}
		layout.addComponent(close);
		layout.setComponentAlignment(close, Alignment.BOTTOM_CENTER);
		mainWindow.addWindow(subwindow);
	}

}